package com.scalar.chiptrack.adaptor.carsem;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;
import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;

import java.io.BufferedInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 17 Dec, 2009
 * Time: 2:40:16 PM
 */
public class CarsemAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String PROTOCOL_SCHEME_HTTPS   = "https";
    private static final String HOST                    = "cc01.carsems.com.my";
    private static final String POST_URI_LOGIN          = "/cccweb/login_result.asp";

    private static final int DEFAULT_SSL_PORT = 443;
    public static final String FILE_NAME_TEST_WIP       = "CARSEM_TEST_WIP";
    public static final String FILE_NAME_WIP            = "CARSEM_WIP_STATUS";
    public static final String FILE_NAME_YIELD          = "CARSEM_YIELD_STATUS";
    public static final String ADAPTOR_NAME             = "CARSEM_WIP";
    private String m_dataOutputDir      = null;
    private Logger m_adaptorLogger      = null;
    private String m_username           = null;
    private String m_password           = null;
    private String m_CustName           = null;
    private String m_CustNo             = null;
    private String downloadFileName     = null;
    private int    m_adaptor_id         = -1;

    public CarsemAdaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_CARCEM, LOCATION_TYPE_ASSEMBLY );
            if( vendorAdaptor == null )
            {
                log( "ERROR!! ERROR!! ERROR!! Exception while loading CarSem Adaptor Username, Password details from database" );
                throw new ScalarException( "Exception while loading CarSem Adaptor Username, Password details from database" );
            }
            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();
            m_CustName     = vendorAdaptor.getCustomerId().split("#")[0];
            m_CustNo     = vendorAdaptor.getCustomerId().split("#")[1];
            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir,VENDOR_NAME_CARCEM );
            AdaptorUtils.setLogger( m_adaptorLogger );
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading Carsem Adaptor Username, Password details from database, Exception: " + se );
            throw new ScalarException( "Exception while loading CarSem Adaptor Username, Password details from database", se );
        }
    }
    public static void main( String[] args ) throws Exception
    {
        new CarsemAdaptor().execute();
    }
    public void execute() throws Exception
    {
         try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
            //Print the header details
            AdaptorUtils.printHeader(VENDOR_NAME_CARCEM, CONSTANT_ADAPTOR);
            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );
            HTTPConnection connection = login( HOST, DEFAULT_SSL_PORT, m_username, m_password );
            if ( connection != null )
            {
                BufferedInputStream bfReader = null;
                //For DownLoading WipStatus Report
                HTTPResponse rsp = requestWipReport( connection );
                if( rsp != null )
                {    
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Wip Status Sheet..." );
                        log( "\tDownloading the Wip Status Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_WIP+"-"+downloadFileName, FILE_EXTN_XLS,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , downloadFileName, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Lot Status Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Wip Status Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Wip Status Sheet" );
                    throw new ScalarException( "Could not create response object of Wip Status Sheet" );
                }
                // For DownLoding the Test WIP Information
                rsp = requestTestWipReport( connection );
                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Test WIP info Sheet..." );
                        log( "\tDownloading the Test WIP info Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_TEST_WIP+"-"+downloadFileName, FILE_EXTN_XLS,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , downloadFileName, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Test WIP Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Test WIP Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Test WIP Sheet" );
                    throw new ScalarException( "Could not create response object of Test WIP Sheet" );
                }

                /*rsp = requestTestYieldReport( connection );
                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Test Yield info Sheet..." );
                        log( "\tDownloading the Test Yield info Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_YIELD+"-"+downloadFileName, FILE_EXTN_XLS,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , downloadFileName , FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Test Yield Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Test Yield Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Test Yield Sheet" );
                    throw new ScalarException( "Could not create response object of Test Yield Sheet" );
                }*/
                // Logging out from Carsem WEB SITE
                //logout( connection );
                bfReader = null;
            }
            else
            {
                log( "Could not able to get the Connection to web site" );
                throw new ScalarException( "Could not able to get the Connection to web site" );
            }
        }
        catch (Exception e )
        {
            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
            System.out.println("Exception while trying to connect and read data from "+HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }
    private HTTPConnection login( String host, int port, String username, String password ) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPConnection conn = new HTTPConnection( PROTOCOL_SCHEME_HTTPS, host, port );
        CookieModule.setCookiePolicyHandler( null );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );
        NVPair defaultHeaders[] = new NVPair[ 8 ];
        defaultHeaders[ 0 ] = new NVPair( "Accept", "*/*" );
        defaultHeaders[ 1 ] = new NVPair( "Referer", "https://" + host );
        defaultHeaders[ 2 ] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[ 3 ] = new NVPair( "Content-Type", "application/x-www-form-urlencoded" );
        defaultHeaders[ 4 ] = new NVPair( "Proxy-Connection", "Keep-Alive" );
        defaultHeaders[ 5 ] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" );
        defaultHeaders[ 6 ] = new NVPair( "Host", host );
        defaultHeaders[ 7 ] = new NVPair( "Pragma", "no-cache" );
        conn.setDefaultHeaders( defaultHeaders );

        HTTPResponse rsp = conn.Get("/cccweb/");

        NVPair[] formData = new NVPair[ 4 ];
        formData[ 0 ] = new NVPair( "username", username );
        formData[ 1 ] = new NVPair( "password", password );

        System.out.print( "Trying to Logging in......" );
        log( "Trying to Logging in......" );
        rsp  = conn.Post( POST_URI_LOGIN, formData, defaultHeaders );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/
        //System.out.println("rsp.getEffectiveUR = " + rsp.getEffectiveURI());
        //System.out.println("rsp.getOriginalURI = " + rsp.getOriginalURI() );


        log( "Response from Server: " + rsp.getStatusCode() + " " + rsp.getReasonLine() );
        if ( rsp.getStatusCode() >= 400 )
        {
            System.out.println( "Login failed.. response from server: " + rsp.getStatusCode() );
            log( "Login failed.. response from server: " + rsp.getStatusCode() );
            conn = null;
        }
        log( "Done." );
        return conn;
    }

    private HTTPResponse requestWipReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse rsp = null;
        
        rsp = conn.Get( "/cccweb/reportfile.asp?customercode="+m_CustName+"&customercodeid="+m_CustNo+"&report=WIP&subpath=WIP" );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/

        System.out.println( "\t\nSubmitting the request for Wip Staus......" );
        log( "\tSubmitting the request for Wip Staus......" );

        CarsemHtmlParser parser = new CarsemHtmlParser();
        parser.parse( new BufferedReader( new InputStreamReader( rsp.getInputStream() ) ) );
        downloadFileName = parser.getFileName();
        rsp = conn.Get( parser.getDownloadLink() );

        return rsp;
    }

    private HTTPResponse requestTestWipReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse rsp = null;
        rsp = conn.Get( "/cccweb/reportfile.asp?customercode="+m_CustName +"&customercodeid="+ m_CustNo + "&report=WIP%20TEST&subpath=WIP%20TEST" );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/
        //SIT#351
        System.out.println( "\t\nSubmitting the request for Test Wip Report......" );
        log( "\tSubmitting the request for Test Wip Reprot......" );

        CarsemHtmlParser parser = new CarsemHtmlParser();
        parser.parse( new BufferedReader( new InputStreamReader( rsp.getInputStream() ) ) );

        downloadFileName = parser.getFileName();

        rsp = conn.Get( parser.getDownloadLink() );

        return rsp;
    }

    private HTTPResponse requestTestYieldReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse rsp = null;
        rsp = conn.Get( "/cccweb/reportfile.asp?customercode="+m_CustName +"&customercodeid="+ m_CustNo + "&report=YIELD&subpath=YIELD" );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/

        System.out.println( "\t\nSubmitting the request for Yield Report......" );
        log( "\tSubmitting the request for Yield Report......" );

        CarsemHtmlParser parser = new CarsemHtmlParser();
        parser.parse( new BufferedReader( new InputStreamReader( rsp.getInputStream() ) ) );
        downloadFileName = parser.getFileName();

        rsp = conn.Get( parser.getDownloadLink() );

        return rsp;
    }

    /**
     *
     *  Logs out from the CARSEM Web Site
     */
    private void logout( HTTPConnection conn ) throws Exception
    {
        try
        {
            System.out.print( "\n Logging out... " );
            log( "\n Logging out... " );
            //HTTPResponse rsp = conn.Get( LOG_OUT );
            System.out.println( "Successfully logged out from CARSEM Site" );
            log( "Successfully logged out from CARSEM Site" );
            conn = null;
            //rsp = null;
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From CARSEM Site" + ignore);
            throw ignore;
        }
    }
    private void log( String message )
    {
        if ( message == null ) return;
        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
